package com.santalu.emptyview;

import ohos.agp.utils.TextTool;
import ohos.app.Context;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;
import javax.net.ssl.SSLException;

/**
 * Created by fatih.santalu on 24.01.2018.
 *
 * @author hw
 * @since 2021/5/27
 */
public enum Error {
    CONNECTION(ResourceTable.String_error_connection_title, ResourceTable.String_error_connection),
    TIMEOUT(ResourceTable.String_error_connection_timeout_title, ResourceTable.String_error_connection_timeout),
    SERVICE(0, 0),
    UNKNOWN(ResourceTable.String_error_unknown_title, ResourceTable.String_error_unknown);

    private final int titleResId;
    private final int messageResId;
    private String message;

    Error(int titleResId, int messageResId) {
        this.titleResId = titleResId;
        this.messageResId = messageResId;
    }

    public static Error get(Throwable throwable) {
        if (throwable instanceof ConnectException || throwable instanceof UnknownHostException) {
            return CONNECTION;
        } else if (throwable instanceof SocketTimeoutException ||
                throwable instanceof TimeoutException ||
                throwable instanceof SSLException) {
            return TIMEOUT;
        } else if (!TextTool.isNullOrEmpty(throwable.getMessage())) {
            SERVICE.message = throwable.getMessage();
            return SERVICE;
        } else {
            return UNKNOWN;
        }
    }

    public int getTitleResId() {
        return titleResId;
    }

    public int getMessageResId() {
        return messageResId;
    }

    public String getTitle(Context context) {
        return titleResId == 0 ? null : context.getString(titleResId);
    }

    public String getMessage(Context context) {
        return messageResId == 0 ? message : context.getString(messageResId);
    }
}